/*
 * File Name:soft_timer_test.c
 * Version:v1.0.0
 * Change Logs:
 * Date             Author      	main change
 * 2025-03-12      	lanxin          the first version
 *
*/

/********************************************* READ ME BEGIN *************************************************************/

/* Brief:
 *
 * *1.对 soft_timer 的测试程序。
 *
 */

/* Notice:
 *
 * *
 *
 */

/********************************************* READ ME END ***************************************************************/

/* source file */
#include "rtthread.h"
#include "soft_timer.h"
#include "stdlib.h"

/* debug define */

/* private define */

/* function declaration */

/* variable declaration */

static void second_timeout ( void *para )
{
	soft_tmr_schedule ( time ( 0 ) );
}

static int init_soft_timer ( void )
{
	soft_tmr_init ( 3, 2048 );
	rt_timer_t tmr_second = rt_timer_create ( "second", second_timeout, 0, 1000, RT_TIMER_FLAG_PERIODIC );

	if ( tmr_second )
	{
		rt_timer_start ( tmr_second );
		rt_kprintf ( "soft timer init down\r\n" );
	}

	return 0;
}

static void tmr_cb ( time_t t_trigger, void *para )
{
	rt_kprintf ( "tmr cb:trigger %d\r\n", ( uint32_t ) t_trigger );
}

static int do_create_tmr ( int argc, char **argv )
{
	if ( argc != 3 )
	{
		rt_kprintf ( "cmd like:do_create triger period\r\n" );
		return -1;
	}

	time_t t_trigger = time ( 0 ) + atoi ( argv[1] );
	uint32_t period = atoi ( argv[2] );

	if ( soft_tmr_create ( t_trigger, tmr_cb, argv, period ) )
		rt_kprintf ( "create tmr:trigger [%d] period [%d]\r\n", ( uint32_t ) t_trigger, ( uint32_t ) period );
	else
	{
		rt_kprintf ( "create soft timer failed\r\n" );
	}

	return 0;
}

static int do_set_tmr_period ( void )
{
	time_t trigger = time ( 0 ) + 1;
	rt_list_t *list_tmr = soft_tmr_create ( trigger, tmr_cb, 0, 2 );

	if ( list_tmr )
	{
		rt_kprintf ( "create tmr:trigger %d period 2\r\n", ( uint32_t ) trigger );
		rt_thread_mdelay ( 10000 );
		rt_kprintf ( "set tmr period to 1\r\n" );
		soft_tmr_set_period ( list_tmr, 1 );
		rt_thread_mdelay ( 5000 );
		rt_kprintf ( "delete tmr\r\n" );
		soft_tmr_delete ( list_tmr );
	}

	return 0;
}

static int do_delete_tmr ( void )
{
	rt_list_t *list_delete_tmr = soft_tmr_create ( time ( 0 ) + 1, tmr_cb, 0, 1 );
	rt_thread_mdelay ( 5000 );
	int res = soft_tmr_delete ( list_delete_tmr );
	rt_kprintf ( "delete soft %s\r\n", res == 0 ? "ok" : "failed" );

	return 0;
}

static int do_delete_all_tmr ( void )
{
	soft_tmr_delete_all();
	return 0;
}

/* 导出到初始化列表 */
INIT_APP_EXPORT ( init_soft_timer );

/* 导出到 MSH 命令列表 */
MSH_CMD_EXPORT ( do_create_tmr, create );
MSH_CMD_EXPORT ( do_set_tmr_period, set period );
MSH_CMD_EXPORT ( do_delete_tmr, delete );
MSH_CMD_EXPORT ( do_delete_all_tmr, delete all );